package cbs.jdtag.actions;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.ParserConfigurationException;

import cbs.jdtag.AppContext;
import cbs.jdtag.DataModel2;
import cbs.jdtag.io.XMLReader;

public class LoadAction extends AbstractAction {

	private static final long serialVersionUID = -3122297277283533965L;
	private transient final Logger logger = Logger.getLogger(this.getClass().getName());
	
	private final JFileChooser fd = new JFileChooser();
	
	public LoadAction() throws ParserConfigurationException {
		super("Load DTAG file");
		
		putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
		
		fd.setFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "DTAG files (*.atag)";
			}
			
			@Override
			public boolean accept(File file) {
				if (file.getName().endsWith(".atag")) {
					return true;
				}
				else if (file.isDirectory()) {
					return true;
				}
				else {
					return false;
				}
			}});
		fd.setMultiSelectionEnabled(false);
		fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
	}
	
	public void actionPerformed(ActionEvent ae) {
		DataModel2 dm = AppContext.getDM();
		
		logger.fine("Executing...");
		
		AppContext.mainView.setTitle("jdtag");
		AppContext.mainView.setCmdInputFieldEnabled(false);
		
		fd.setCurrentDirectory(new File(AppContext.getRecentlyUsedDir()));
		int retVal = fd.showDialog(AppContext.mainView, "Load DTAG file");
		
		if (retVal == JFileChooser.APPROVE_OPTION) {
			
			AppContext.setRecentlyUsedDir(fd.getCurrentDirectory().getPath());
			
			try {
				dm.reset();
				dm.setAlignmentFile(fd.getSelectedFile());
				XMLReader.parseATAGFile(dm.getAlignmentFile().toURI());
				AppContext.mainView.setTitle("jdtag: " + dm.getAlignmentFile());
				AppContext.mainView.setCmdInputFieldEnabled(true);
				AppContext.mainView.setStatusText("File loaded.");
			}
			catch (Exception e) {
				logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
				JOptionPane.showMessageDialog(AppContext.mainView,
						e.getLocalizedMessage(), "Parse error",
						JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				AppContext.mainView.setStatusText("Parse error.");
				return;
			}
		}
	}
}
